package com.booth.base.services.impl;

import java.util.ArrayList;
import java.util.List;

import com.booth.base.model.Modules;
import com.booth.base.services.IModulesService;

public class ModulesService
implements IModulesService
{
	private List<Modules> lstAll;

	public List<Modules> showModulesTree( Short status )
	{
		if ( status == null )
		{
			this.lstAll = Modules.dao.findAll();
		}else {
			this.lstAll = Modules.dao.find( "select * from modules where status=? order by show_order asc", new Object[] { status } );
		}
		List lstTree = findById( null );
		return(lstTree);
	}


	public List<Modules> showUseModulesTree()
	{
		this.lstAll = Modules.dao.find( "select id,parent_id,name as text from modules where status!=0 order by show_order asc" );

		List lstTree = findById( null );
		return(lstTree);
	}


	public List<Modules> showUserGroupMenu( Integer gid )
	{
		this.lstAll = Modules.dao.findGroupAvalibe( gid );

		List lstTree = findById( null );
		return(lstTree);
	}


	private List<Modules> findById( Integer parentId )
	{
		List subs = new ArrayList();
		for ( int i = 0; i < this.lstAll.size(); i++ )
		{
			Modules mod = (Modules) this.lstAll.get( i );
			if ( parentId == null )
			{
				if ( (mod.get( "parent_id" ) != null) && ( ( (Integer) mod.get( "parent_id" ) ).intValue() != 0) )
					continue;
				this.lstAll.remove( i );
				i--;
				List modSubs = findById( mod.getInt( "id" ) );
				if ( modSubs.size() > 0 )
				{
					mod.put( "children", modSubs );
				}
				subs.add( mod );
			}else  {
				if ( (mod.get( "parent_id" ) == null) || ( ( (Integer) mod.get( "parent_id" ) ).intValue() != parentId.intValue() ) )
					continue;
				List modSubs = findById( mod.getInt( "id" ) );
				if ( modSubs.size() > 0 )
				{
					mod.put( "children", modSubs );
				}
				subs.add( mod );
			}
		}

		return(subs);
	}


	public List<Modules> showEnableModulesTree( Short type )
	{
		StringBuffer sb = new StringBuffer( "select id,parent_id,name as text from modules where status=9 " );
		if ( (type != null) && (type.shortValue() > 0) )
		{
			sb.append( "and type<" + type );
		}
		sb.append( " order by show_order asc" );
		this.lstAll = Modules.dao.find( sb.toString() );
		List lstTree = findById( null );
		return(lstTree);
	}


	@Override
	public List<Modules> showParentModules(Short type,Integer id) {
		StringBuffer sb = new StringBuffer( "select id,parent_id,name as text from modules where status=9 " );
		if ( (type != null) && (type.shortValue() > 0) )
		{
			sb.append( " and type= " + type );
		}
		if (id != null && id > 0)
		{
			sb.append( " and id != "+id );
		}
		sb.append( " order by show_order asc" );
		this.lstAll = Modules.dao.find( sb.toString() );
		return lstAll;
	}
}